<?php


namespace app\wechat\controller;


use app\BaseController;
use Composer\Autoload\ClassLoader;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\console\command\VendorPublish;
use think\exception\ValidateException;
use think\facade\Db;

class Tool extends AuthBase
{
    protected $noLogin = ['getCity'];
    public function conversion()
    {
        $data = input('post.');
        try {
            validate(\app\wechat\validate\Order::class)
                ->scene('calculate')
                ->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return show(0, $e->getError());
        }
        $goods_one = Db::name('goods')
            ->where('id', $data['supply_id'])
            ->find();
        $goods_two = Db::name('goods')
            ->where('id', $data['need_id'])
            ->find();
        $num = round($data['supply_number'] / $goods_one['ratio'] * $goods_two['ratio'], 2);
//        dd($num);
        //转成整数
        return show(1, '', $num);
    }

    /**\
     * 上传图片
     */
    public function upload_img()
    {
        // 获取上传图片信息
        $file = request()->file('img');
        if ($file->getSize() >= 2048576) {
            return show(0, '上传图片过大');
        }
        $ext = pathinfo($file->getOriginalName(), PATHINFO_EXTENSION);
        $img_arr = ['jpg', 'jpeg', 'png'];
        if (!in_array($ext, $img_arr)) {
            return show(0, '请上传图片');
        }

        // 图片存储在本地的临时路经
        $filePath = $file->getRealPath();
        //做木马校验
        $res_muma = checkHex($filePath);
        if (!$res_muma){
            return show(0,'文件不合法');
        }
        // 获取图片后缀
        $ext = $file->getOriginalExtension();
        // 上传到七牛后保存的新图片名
        $newImageName = date('Y') . '/' . date('m') . '/' . substr(md5($file->getOriginalName()), 0, 6)
            . date('YmdHis') . rand(00000, 99999) . '.' . $ext;
        // 说明：为了方便阅读，上一行代码进行的回车，如果你的遇到了问题，请放到一行
        // 构建鉴权对象
        $auth = new Auth(config('qiniu.ak'), config('qiniu.sk'));
        // 要上传的空间位置
        $token = $auth->uploadToken(config('qiniu.bucket_index'));
        //域名
        $domain = config('qiniu.domain');
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $newImageName, $filePath);
        if ($err !== null) {
            return null;
        } else {
            $data['url'] = 'http://' . $domain . '/' . $newImageName;
            //校验图片是否合法
            $res = $this->img_check($data['url']);
            if ($res !== "pass") {
                $this->img_delete($newImageName);
                return show(0, '对不起图片涉嫌违法内容!');
            } else {
                return show(1, '', $data);
            }
        }
    }


    /**\
     * 上传视频
     */
    public function upload_video()
    {
        // 获取上传图片信息
        $file = request()->file('img');
        if ($file->getSize() >= 104857600) {
            return show(0, '上传视频过大');
        }
        $ext = pathinfo($file->getOriginalName(), PATHINFO_EXTENSION);
        $img_arr = ['mp4'];
        if (!in_array($ext, $img_arr)) {
            return show(0, '请上传视频');
        }
        // 图片存储在本地的临时路经
        $filePath = $file->getRealPath();
        // 获取图片后缀
        $ext = $file->getOriginalExtension();
        // 上传到七牛后保存的新图片名
        $newImageName = date('Y') . '/' . date('m') . '/' . substr(md5($file->getOriginalName()), 0, 6)
            . date('YmdHis') . rand(00000, 99999) . '.' . $ext;
        // 说明：为了方便阅读，上一行代码进行的回车，如果你的遇到了问题，请放到一行


        // 构建鉴权对象
        $auth = new Auth(config('qiniu.ak'), config('qiniu.sk'));
        // 要上传的空间位置
        $token = $auth->uploadToken(config('qiniu.bucket_index'));
        //域名
        $domain = config('qiniu.domain');
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $newImageName, $filePath);
        if ($err !== null) {
            return null;
        } else {
            $data['url'] = 'http://' . $domain . '/' . $newImageName;
            //校验视频是否合法
            $res = $this->video_check($data['url']);
            if ($res !== "pass") {
                $this->img_delete($newImageName);
                return show(0, '对不起视频涉嫌违法内容!', $data['url']);
            } else {
                return show(1, '', $data);
            }
        }
    }

    /**\
     * @param $delFileName
     * @return bool
     * 删除图片
     */
    public function img_delete($delFileName)
    {
        $conf = config('qiniu');

        // 构建鉴权对象
        $auth = new Auth(config('qiniu.ak'), config('qiniu.sk'));
        // 配置
        $config = new \Qiniu\Config();
        // 管理资源
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
        // 删除文件操作
        $res = $bucketManager->delete(config('qiniu.bucket_index'), $delFileName);
        if (is_null($res)) {
            // 为null成功
            return true;
        }
        return false;

    }

    /**\
     *图片审核
     */
    public function img_check($image)
    {
        //参数填充
        $url = 'http://ai.qiniuapi.com/v3/image/censor';
        $method = "POST";

        $host = "ai.qiniuapi.com";

        $contentType = "application/json";

        $body = "{ \"data\": {\"uri\": \"" . $image . "\"},\"params\": {\"scenes\":[\"pulp\",\"terror\",\"politician\"]}}";

        //Header，鉴权凭证

        $auth = new Auth('r9in76LoqoZWNQNr7x0qkqJ6hM8-HnQ4kOF0VbZ4', 'lKYIaXyXRSfV06nEWlnbnpkF2itdRVp7eUBYsPfF');

        $headers = $auth->authorizationV2($url, $method, $body, $contentType);

        $headers['Content-Type'] = $contentType;

        $headers['Host'] = $host;

        $response = \Qiniu\Http\Client::post($url, $body, $headers);

        //拿到$response返回值，返回所需要的数据

        $ret = json_decode($response->body);
        if (isset($ret->code) && $ret->code == 200) {
            return $ret->result->suggestion;
        } else {

            return $ret->error;
        }
    }

    /**\
     *视频审核
     */
    public function video_check($video)
    {
        //参数填充
        $url = 'http://ai.qiniuapi.com/v3/video/censor';
        $method = "POST";

        $host = "ai.qiniuapi.com";

        $contentType = "application/json";

        $body = "{ \"data\": {\"uri\": \"" . $video . "\"},\"params\": {\"scenes\":[\"pulp\",\"terror\",\"politician\",]}}";

        //Header，鉴权凭证

        $auth = new Auth('r9in76LoqoZWNQNr7x0qkqJ6hM8-HnQ4kOF0VbZ4', 'lKYIaXyXRSfV06nEWlnbnpkF2itdRVp7eUBYsPfF');

        $headers = $auth->authorizationV2($url, $method, $body, $contentType);

        $headers['Content-Type'] = $contentType;

        $headers['Host'] = $host;

        $response = \Qiniu\Http\Client::post($url, $body, $headers);

        //拿到$response返回值，返回所需要的数据

        $ret = json_decode($response->body);

        if (isset($ret->code) && $ret->code == 200) {

            return $ret->result->suggestion;

        } else {

            return $ret->error;
        }

    }
    /**
     * 通过经纬度获取城市
     */
    public function getCity(){
        $lon=input('get.lon');
        $lat=input('get.lat');
        $res=get_geocode($lon,$lat);
        if (!$res['status'] || $res['status']!=1){
            return show(0,'获取信息报错');
        }
//        $where=[];
        $res=$res['regeocode']['addressComponent'];
//        if ($res[''])$res
        if ($res['province'] && !$res['city']){
            $res['city']=$res['province'];
        }
//        if (is_array($res['city'])){
//            return show(0,'获取地址报错');
//        }
        $data['prov']=$res['province'];
        $data['city']=$res['city'];
        return show(1,'',$data);
    }
    /**
     * 文章详情
     */
    public function article_detail(){
        $id=input('get.id');
        $model=Db::name('article')
        ->where('id',$id)
        ->find();
        return show(1,'',$model);
    }
}